package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson2.JSON;
import com.atguigu.common.es.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallESconfig;
import com.atguigu.gulimall.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service("productSaveService")
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public void upProduct(List<SkuEsModel> list) throws IOException {


        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : list) {
            IndexRequest request = new IndexRequest("product");
            request.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            request.source(jsonString, XContentType.JSON);

            bulkRequest.add(request);

        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallESconfig.COMMON_OPTIONS);
    }
}
